package com.xgpro.pc.rolemanage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.PageResult;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.domain.rolemanage.dto.PermissionDTO;
import com.xgpro.domain.rolemanage.dto.RoleDTO;
import com.xgpro.domain.rolemanage.entity.Permissions;
import com.xgpro.domain.rolemanage.entity.Role;
import com.xgpro.mapper.rolemanage.PermissionsMapper;
import com.xgpro.mapper.rolemanage.RoleMapper;
import com.xgpro.pc.rolemanage.service.PermissionsService;
import com.xgpro.pc.rolemanage.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.security.Permission;
import java.util.*;

/**
 * @program: xgpro__dev
 * @Description: 角色
 * @Author: likai
 * @Date: 2019-09-07 16:31
 **/


@Service
@Transactional(readOnly = false)
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private PermissionsService permissionsService;

    @Resource
    private PermissionsMapper permissionsMapper;

    @Override
    public ResponseResult addRole(Role role) {
        int ret = roleMapper.insert(role);
        if (ret > 0) {

            //分配权限
            Set<Permissions> permissions = role.getPermissions();
            if (!CollectionUtils.isEmpty(permissions)) {
                for (Permissions permission : permissions) {

                    roleMapper.assignPers(role.getId(), permission.getId());
                }
            }
            return ResponseResult.ok();
        } else {
            return ResponseResult.failure(ResultCodeEnum.ADD_FAILE.getCode(), ResultCodeEnum.ADD_FAILE.getMessage());
        }
    }

    @Override
    public ResponseResult deleteRole(List<Integer> ids) {
        int ret = -1;
        if (!CollectionUtils.isEmpty(ids)) {
            for (Integer id : ids) {
                int cnt = roleMapper.queryCountByRoleId(id);
                //角色已经被使用，无法删除
                if (cnt > 0) {
                    throw new BusinessRuntimeException(ResultCodeEnum.CAN_NOT_DELETE_ROLE.getCode(), ResultCodeEnum.CAN_NOT_DELETE_ROLE.getMessage());
                }

                //删除对应角色
                ret = roleMapper.deleteByPrimaryKey(id);

                if (ret > 0) {
                    //删除角色权限中间表
                    roleMapper.deleteRolePer(id);
                    return ResponseResult.ok();

                } else {
                    return ResponseResult.failure(ResultCodeEnum.ADD_FAILE.getCode(), ResultCodeEnum.ADD_FAILE.getMessage());
                }
            }
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult updateRole(Role role) {
        int ret = roleMapper.updateByPrimaryKeySelective(role);
        if (ret > 0) {
            //删除角色权限中间表
            roleMapper.deleteRolePer(role.getId());

            //分配权限
            Set<Permissions> permissions = role.getPermissions();
            if (!CollectionUtils.isEmpty(permissions)) {
                for (Permissions permission : permissions) {

                    roleMapper.assignPers(role.getId(), permission.getId());
                }
            }
            return ResponseResult.ok();
        } else {
            return ResponseResult.failure(ResultCodeEnum.ADD_FAILE.getCode(), ResultCodeEnum.ADD_FAILE.getMessage());
        }
    }

    /**
     * 条件查询角色列表
     *
     * @param pageNum
     * @param pageSize
     * @param param
     * @return
     */
    @Override
    public ResponseResult getRole(int pageNum, int pageSize, Map<String, Object> param) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();

        String name = (String) param.get("name");
        String description = (String) param.get("description");
        String createTime = (String) param.get("createTime");
        Object id1 = param.get("id");
        Integer id = null;
        if (!ObjectUtils.isEmpty(id1)) {
            id = Integer.parseInt(id1.toString());
        }

        if (!StringUtils.isEmpty(name)) {
            criteria.andLike("roleName", "%" + name + "%");
        }
        if (!StringUtils.isEmpty(description)) {
            criteria.andLike("description", "%" + description + "%");
        }
        if (!ObjectUtils.isEmpty(id)) {
            criteria.andEqualTo("id", id);
        }
        if (!StringUtils.isEmpty(createTime)) {

            String startTime = createTime.split("/")[0];
            String endTime = createTime.split("/")[1];
            criteria.andLessThanOrEqualTo("createTime", endTime);
            criteria.andGreaterThanOrEqualTo("createTime", startTime);
        }

        PageHelper.startPage(pageNum, pageSize);
        Page<Role> roles = (Page<Role>) roleMapper.selectByExample(example);

        List<RoleDTO> list = new ArrayList<>();
        List<Role> result = roles.getResult();
        if (!CollectionUtils.isEmpty(result)) {
            for (Role role : result) {
                Set<String> menu = new HashSet<>();
                Set<String> points = new HashSet<>();
                List<Permissions> permissions = permissionsMapper.findListByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(permissions)) {
                    for (Permissions permission : permissions) {
                        if ("1".equals(permission.getType())) {
                            menu.add(permission.getPermissionsName());
                        } else if ("2".equals(permission.getType())) {
                            points.add(permission.getPermissionsName());
                        }
                    }
                }
                RoleDTO roleDTO = new RoleDTO();
                BeanUtils.copyProperties(role, roleDTO);
                roleDTO.setMenu(menu);
                roleDTO.setPoint(points);
                list.add(roleDTO);

            }
        }

        PageResult pageResult = new PageResult(roles.getTotal(), list, pageNum);
        return ResponseResult.ok(pageResult);
    }

    /**
     * 获取角色详情
     *
     * @param roleId
     * @return
     */
    @Override
    public RoleDTO findOne(Integer roleId) {

        Role role = roleMapper.selectByPrimaryKey(roleId);

        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(role, roleDTO);

        List<Permissions> permissions = permissionsMapper.findListByRoleId(roleId);
        Set<Permissions> set = new HashSet<>(permissions);

        roleDTO.setSetPoint(set);
        return roleDTO;
    }

    @Override
    public List<Permissions> findPermListByRoleId(Integer roleId) {

        return roleMapper.findPermListById(roleId);
    }
}